import 'dart:developer';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:loongson_block/animation/progress.dart';
import 'package:loongson_block/utils/state.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class WebMain extends StatelessWidget {
  const WebMain({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Obx(
        () => Column(children: [
          AnimatedProgressIndicator(value: (progressPer.value / 100).toDouble()),
          Expanded(child: WebViewExample(ip: ip.value))
        ]),
      )),
    );
  }
}

class WebViewExample extends StatefulWidget {
  final String ip;
  const WebViewExample({Key? key, required this.ip}) : super(key: key);

  @override
  WebViewExampleState createState() => WebViewExampleState();
}

class WebViewExampleState extends State<WebViewExample> {
  @override
  void initState() {
    super.initState();
    // Enable virtual display.
    if (Platform.isAndroid) WebView.platform = AndroidWebView();
  }

  @override
  void dispose() {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WebView(
      initialUrl: 'http://${widget.ip}:3000',
      javascriptMode: JavascriptMode.unrestricted,
      debuggingEnabled: true,
      onProgress: (int per) {
        log('process $per');
        progressPer.value = per;
      },
      onPageStarted: (String str) {
        log('start $str');
        EasyLoading.show(status: '加载中...');
      },
      onPageFinished: (String str) {
        log('finish $str');
        EasyLoading.showSuccess('加载成功');
      },
      onWebResourceError: (_) {
        log('error');
        Get.back();
        EasyLoading.showError('加载失败 请重新输入IP。');
      },
      allowsInlineMediaPlayback: true,
    );
  }
}
